package permission

import (
	"context"
	"fmt"
	"github.com/samber/lo"
	"private-domain-overseas-service/admin/business/api/internal/repository/permission"
	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"
	"private-domain-overseas-service/pkg/status/bizadmin"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/adminrole"
	"private-domain-overseas-service/tools/ent/adminrouter"
	"private-domain-overseas-service/tools/ent/predicate"
	"strconv"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminRouterRoleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewAdminRouterRoleLogic - 角色菜单接口
func NewAdminRouterRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminRouterRoleLogic {
	return &AdminRouterRoleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminRouterRoleLogic) AdminRouterRole(req *types.RoleAdminRouterRequest) (resp *types.RoleAdminRouterResponse, err error) {
	adminRoleDAO := permission.NewAdminRoleDao(l.ctx, l.svcCtx)
	adminRouterDAO := permission.NewAdminRouterDao(l.ctx, l.svcCtx)

	// 角色id为0，直接返回
	if req.RoleId == 0 {
		return nil, xerr.ErrCodeMsg(xerr.ServerRequestParamError, "角色不存在")
	}

	// 根据id查询角色
	adminRoleConditions := make([]predicate.AdminRole, 0, 1)
	adminRoleConditions = append(adminRoleConditions, adminrole.IDEQ(int(req.RoleId)))
	adminRole, err := adminRoleDAO.AdminRoleFirst(adminRoleConditions)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("查询角色失败: %v", err.Error()))
	}

	// 从角色中获取路由id
	routerIds := strings.Split(adminRole.AdminRoleRouterIds, ",")
	intRouteIds := lo.Map(routerIds, func(item string, _ int) int {
		id, _ := strconv.Atoi(item)
		return id
	})

	// 查询路由
	adminRouterConditions := make([]predicate.AdminRouter, 0, 2)
	adminRouterConditions = append(adminRouterConditions, adminrouter.AdminRouterStatusEQ(bizadmin.StatusEnabled))
	allRouters, _, err := adminRouterDAO.AdminRouterConditionsAll(adminRouterConditions)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("查询路由失败: %v", err.Error()))
	}

	// 查询路由列表
	parents := lo.Map(allRouters, func(item *ent.AdminRouter, _ int) int64 {
		return item.AdminRouterPid
	})
	adminRouterConditions = append(adminRouterConditions, adminrouter.IDIn(intRouteIds...))
	adminRouters, _, err := adminRouterDAO.AdminRouterConditionsAll(adminRouterConditions)
	if err != nil {
		return nil, err
	}

	// 剔除有孩子的路由，方便前端展示
	// 所有路由id
	ids := lo.Map(adminRouters, func(item *ent.AdminRouter, _ int) int64 {
		return int64(item.ID)
	})
	// 剔除父路由id
	result := lo.Filter(ids, func(item int64, _ int) bool {
		return !lo.Contains(parents, item)
	})

	// 返回数据
	return &types.RoleAdminRouterResponse{
		Ids: result,
	}, nil
}
